// import { messages } from '@/bimai_plugin/components/common/Message.vue';
/*
 * @Descripttion: 
 * @version: 
 * @Author: sueRimn
 * @Date: 2022-02-15 17:15:36
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2022-03-04 11:52:49
 */
import Axios, { AxiosInstance, AxiosRequestConfig } from 'axios'
import { getBaseURL } from '@/service/BaseURL'
import { ElMessage } from 'element-plus'
import { getCookie, setCookie } from '@/utils/cookie'

const baseURL = getBaseURL()
const axios: AxiosInstance = Axios.create({

    baseURL: baseURL,
    timeout: 20000, // 请求超时 20s
})
interface IAxiosRequestConfig extends AxiosRequestConfig {
    showError?: boolean
}

// 前置拦截器（发起请求之前的拦截）
axios.interceptors.request.use(
    (config: IAxiosRequestConfig): IAxiosRequestConfig => {
        config.headers.Authorization = getCookie('bimai_admin_token')
        const configProps = config || {}
        configProps.params = config.params ? config.params : {}
        let params = config.data || undefined
        params = params ? JSON.stringify(params) : ''
        return configProps
    }, err => {
        ElMessage.error({ message: '请求超时!' });
        return Promise.resolve(err);
    }
)


// 后置拦截器（获取到响应时的拦截）
axios.interceptors.response.use(
    (response) => {
        if (response.status == 200) {
            if (response.data.code == 200 || !response.data.code) {
                // 无code 代表 特殊下载接口
                return response.data
            } else if (response.data.code == 100009) {
                setTimeout(() => {
                    setCookie('bimai_admin_token', '', -1, '/') // 清除token
                    setCookie('user_info', '', -1) // 清除user_info
                    window.location.href = process.env.NODE_ENV == 'development' ? '/' : '/admin/#'
                }, 2000);
                return Promise.reject(response.data.message)
            } else {
                return Promise.reject(response.data.message)
            }
        } else {
            return Promise.reject('未知错误！')
        }
    },
    (error) => {
        if (error.message.indexOf('timeout') != -1) {
            return Promise.reject('接口请求超时，请刷新后在操作！')
        } else {
            return Promise.reject('网络错误！')
        }
    }
)

export default axios
